package com.biscuit.page.basicservice.persistence.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biscuit.page.basicservice.model.entities.mysql.SysUser;
import com.biscuit.page.basicservice.model.entities.mysql.SysUserDetail;
import com.biscuit.page.basicservice.persistence.mapper.UserMapper;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import com.biscuit.page.basicservice.utils.RegexUtil;
import com.biscuit.page.basicservice.utils.WrapperUtil;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @author biscuit
 * @createTime 2024/6/11 10:07
 */
@Component
public class UserDao extends ServiceImpl<UserMapper, SysUser> {

    public void updatePasswordByUserId(Long userId, String defaultPassword) {
        LambdaUpdateWrapper<SysUser> updateWrapper = WrapperUtil.instanceUpdate(SysUser.class)
                .set(SysUser::getPassword, defaultPassword)
                .eq(SysUser::getId, userId);
        super.update(updateWrapper);
    }

    public SysUser getByAccount(String account) {
        // 提前声明匹配标识
        boolean flag = false;

        // 提前构建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = WrapperUtil.instanceQuery(SysUser.class);

        // 判断账号是否为邮箱
        if (RegexUtil.validateEmail(account)) {
            queryWrapper.eq(SysUser::getEmail, account);
            flag = Boolean.TRUE;
        }

        // 判断账号是否为手机号
        if (!flag && RegexUtil.validateMobile(account)) {
            queryWrapper.eq(SysUser::getMobile, account);
            flag = Boolean.TRUE;
        }

        // 判断账号类型是否合法
        BaseExceptionUtil.throwException(flag, "账号类型错误");

        // 查询用户信息
        return super.getOne(queryWrapper);
    }

    public void insertAndIncrement(SysUser sysUser) {
        baseMapper.insertAndIncrement(sysUser);
    }

    public void updateLastLoginTime(Long id, LocalDateTime loginTime) {
        LambdaUpdateWrapper<SysUser> updateWrapper = WrapperUtil.instanceUpdate(SysUser.class)
                .eq(SysUser::getId, id)
                .set(SysUser::getLastLoginTime, loginTime);
        super.update(updateWrapper);
    }

    public List<SysUser> listByEmail(String email) {
        LambdaQueryWrapper<SysUser> wrapper = WrapperUtil.instanceQuery(SysUser.class)
                .eq(SysUser::getEmail, email);
        return super.list(wrapper);
    }

    public List<SysUser> listByMobile(String mobile) {
        LambdaQueryWrapper<SysUser> wrapper = WrapperUtil.instanceQuery(SysUser.class)
                .eq(SysUser::getMobile, mobile);
        return super.list(wrapper);
    }
}
